﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using Billing.WindowsBase;
using Billing.DataObjects;
using System.Reflection;

namespace Billing.Windows.Shell.SystemObjects
{
    public partial class DLLsForm : BaseList
    {
        ShellDataContext mShellDataContext = new ShellDataContext();
        #region Constructors
        public DLLsForm()
            : this(true)
        {
        }

        public DLLsForm(bool Register)
            : base(Register)
        {
            InitializeComponent();
        }

        #endregion

        #region Overrides
        protected override void onDataLoad()
        {
            base.onDataLoad();
            this.bsElement.DataSource = mShellDataContext.DLLs;
            this.ElementRowTemplate = ultraGridRowEditTemplate1;
        }
        protected override void onAfterInitialize()
        {
            base.onAfterInitialize();
            this.ElementNameID = "dllID";

        }
        protected override void onDelete()
        {
            try
            {
                base.onDelete();
                bsElement.RemoveCurrent();
                //mShellDataContext.SubmitChanges();
                this.onDataLoad();
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }

        }
        protected override void onSave()
        {
            base.onSave();
            mShellDataContext.SubmitChanges();
        }
        protected override void onClose()
        {
            if ( AllowSave && ( mShellDataContext.GetChangeSet().Deletes.Count > 0
                || mShellDataContext.GetChangeSet().Updates.Count > 0
                || mShellDataContext.GetChangeSet().Inserts.Count > 0))
            {
                if (MessageBox.Show("შევინახო შეცვლილი მონაცემები?", "", MessageBoxButtons.YesNo) == DialogResult.Yes)
                    mShellDataContext.SubmitChanges();
            }
            base.onClose();
        }
        protected override void onElementInitializeLayout(object sender, Infragistics.Win.UltraWinGrid.InitializeLayoutEventArgs e)
        {
            base.onElementInitializeLayout(sender, e);
            grd.DisplayLayout.Override.CellClickAction = Infragistics.Win.UltraWinGrid.CellClickAction.RowSelect;
            if (e.Layout.Bands[0].Columns.Count > 0)
            {
                e.Layout.Bands[0].Columns["Value"].Hidden = true;
                e.Layout.Bands[0].Columns["Object"].Hidden = true;
                e.Layout.Bands[0].Columns["ModifierID"].Hidden = true;
                e.Layout.Bands[0].Columns["ModifiedDate"].Hidden = true;
                e.Layout.Bands[0].Columns["StatusID"].Hidden = true;
                e.Layout.Bands[0].Columns["SID"].Hidden = true;
                e.Layout.Bands[0].Columns["CurrentObject"].Hidden = true;
                e.Layout.Bands[0].Columns["PATH"].Hidden = true;
                e.Layout.Bands[0].Columns["Version"].Hidden = true;

                e.Layout.Bands[0].Columns["ID"].Header.Caption = "ინდექსი";
                e.Layout.Bands[0].Columns["Key"].Header.Caption = "უნიკალური ველი";
                e.Layout.Bands[0].Columns["Name"].Header.Caption = "სახელი";
                e.Layout.Bands[0].Columns["FullName"].Header.Caption = "სრული გზა";
                e.Layout.Bands[0].Columns["CreatorID"].Header.Caption = "შემქმნელი";
                e.Layout.Bands[0].Columns["CreatedDate"].Header.Caption = "შექმნის თარიღი";
            }
        }
        #endregion

        private void btnTemplateOk_Click(object sender, EventArgs e)
        {
            // This code was automatically generated by the RowEditTemplate Wizard
            // 
            // Close the template and save any pending changes.
            this.ultraGridRowEditTemplate1.Close(true);

        }

        private void btnTemplateCancel_Click(object sender, EventArgs e)
        {
            // This code was automatically generated by the RowEditTemplate Wizard
            // 
            // Close the template and discard any pending changes.
            this.ultraGridRowEditTemplate1.Close(false);

        }

        private void btnTemplateOk_Click_1(object sender, EventArgs e)
        {
            // This code was automatically generated by the RowEditTemplate Wizard
            // 
            // Close the template and save any pending changes.
            if (comboBox1.SelectedIndex == 0)
            {
                grd.Selected.Rows[0].Cells["StatusID"].Value = 1;
            }
            else
            {
                grd.Selected.Rows[0].Cells["StatusID"].Value = 0;
            }
            this.ultraGridRowEditTemplate1.Close(true);

        }

        private void btnTemplateCancel_Click_1(object sender, EventArgs e)
        {
            // This code was automatically generated by the RowEditTemplate Wizard
            // 
            // Close the template and discard any pending changes.
            this.ultraGridRowEditTemplate1.Close(false);

        }

        public static bool PropertySearchCriteria(MemberInfo objMemberInfo, Object objSearch)
        {
            PropertyInfo propertyInfo = (PropertyInfo)objMemberInfo;
            object[] Attributes = propertyInfo.GetCustomAttributes(objSearch as Type, true);

            return (Attributes.Length > 0 && propertyInfo.PropertyType == typeof(bool));
        }

        private void openFileDialog_FileOk(object sender, CancelEventArgs e)
        {
            Cursor = Cursors.WaitCursor;
            MemberInfo[] memberInfos = null;
            bool isListForm = false;
            bool isEditorForm = false;
            int count = 0;
            int counter = 0;
            int value = 0;
            foreach (string fileName in openFileDialog.FileNames)
            {
                Type[] types = Assembly.LoadFile(fileName).GetTypes();
                count = types.Length;
                foreach (Type type in types)
                {
                    counter++;
                    if (type.BaseType == typeof(BaseList))
                    {
                        isListForm = true;
                        isEditorForm = false;
                    }
                    else
                    {
                        if (type.BaseType == typeof(BaseEditor))
                        {
                            isEditorForm = true;
                            isListForm = false;
                        }
                        else
                        {
                            isEditorForm = false;
                            isListForm = false;
                        }
                    }

                    string propertyes = String.Empty;
                    memberInfos = type.FindMembers(MemberTypes.Property, BindingFlags.Public | BindingFlags.Instance | BindingFlags.FlattenHierarchy, new MemberFilter(PropertySearchCriteria), typeof(RightAttributeExistence));

                    foreach (MemberInfo memberInfo in memberInfos)
                    {
                        object[] Attributes = memberInfo.GetCustomAttributes(typeof(RightAttributeExistence), true);
                        string name = ((RightAttributeExistence)(Attributes[0])).Name;

                        if (name == String.Empty)
                        {
                            name = memberInfo.Name;
                        }

                        if (
                                (isEditorForm && (Convert.ToBoolean(((PropertyInfo)memberInfo).GetValue(Activator.CreateInstance(type, eOpenMode.New), null))))
                                || (isListForm && (Convert.ToBoolean(((PropertyInfo)memberInfo).GetValue(Activator.CreateInstance(type), null))))
                                || (isEditorForm && isListForm)
                            )
                        {
                            propertyes = string.Format("{0}{1},", propertyes, memberInfo.Name);

                            mShellDataContext.AddRightProperties(name, memberInfo.Name, type.FullName);
                        }
                    }
                    //string s = s.Trim('\'');
                    mShellDataContext.DeleteRightProperty(propertyes.TrimEnd(','), type.FullName);
                    //new DLLsDB().Delete(propertyes.TrimEnd(','), type.FullName);

                    memberInfos = type.FindMembers(MemberTypes.Property, BindingFlags.Public | BindingFlags.Instance | BindingFlags.FlattenHierarchy, new MemberFilter(PropertySearchCriteria), typeof(RightAttribute));
                    foreach (MemberInfo memberInfo in memberInfos)
                    {
                        object[] Attributes = memberInfo.GetCustomAttributes(typeof(RightAttribute), true);
                        string name = ((RightAttribute)(Attributes[0])).Name;

                        if (name == String.Empty)
                        {
                            name = memberInfo.Name;
                        }

                        propertyes = string.Format("{0}{1},", propertyes, memberInfo.Name);

                        mShellDataContext.AddRightProperties(name, memberInfo.Name, type.FullName);
                    }

                    mShellDataContext.DeleteRightProperty(propertyes.TrimEnd(','), type.FullName);
                }
                counter = 0;
            }
            Cursor = Cursors.Arrow;
        }

        private void propertyGenerator_Click(object sender, EventArgs e)
        {
            this.openFileDialog.ShowDialog();
        }

        private void ultraGridRowEditTemplate1_Enter(object sender, EventArgs e)
        {
            if (Convert.ToInt32(grd.Selected.Rows[0].Cells["StatusID"].Value) == 0)
            {
                comboBox1.SelectedIndex = 1;
            }
            else
            {
                comboBox1.SelectedIndex = 0;
            }
        }
    }
}
